package com.shujia.flink.sql

import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._

object Demo10TopN {
  def main(args: Array[String]): Unit = {

    /**
      * 每隔10秒统计单词的数量，取出每个窗口内单词数量前2的单词
      *
      */


    //flink  流处理的环境
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //设置flink  sql 配置
    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() // 使用blink 的计划器（解析sql）
      .inStreamingMode()
      .build()

    //创建table 环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)


    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE words (
        |  word STRING,
        |  ts AS PROCTIME()
        |) WITH (
        |  'connector' = 'kafka',
        | 'topic' = 'words',
        | 'properties.bootstrap.servers' = 'master:9092',
        | 'properties.group.id' = 'asdasd',
        | 'format' = 'csv',
        | 'scan.startup.mode' = 'earliest-offset',
        | 'csv.ignore-parse-errors' = 'true'
        |)
        |
        |
      """.stripMargin)


    bsTableEnv.executeSql(
      """
        |CREATE TABLE print_table(
        |word STRING,
        |end_time TIMESTAMP(3),
        |c BIGINT,
        |r BIGINT
        |) WITH ('connector' = 'print')
        |
    """.stripMargin)


    /**
      * 已时间和排名作为主键
      *
      */
    bsTableEnv.executeSql(
      """
        |CREATE TABLE mysql_sink(
        |word STRING,
        |end_time TIMESTAMP(3),
        |c BIGINT,
        |r BIGINT,
        |PRIMARY KEY (end_time,r) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/test',
        |   'table-name' = 'topn',
        |   'username'='root',
        |   'password'='123456'
        |)
        |
    """.stripMargin)


    bsTableEnv.executeSql(
      """
        |insert into mysql_sink
        |select * from (
        |select
        |word,
        |end_time,
        |c,
        |row_number() over(partition by end_time order by c desc) as r
        |from
        |(
        |select
        | word,
        | TUMBLE_END(ts, INTERVAL '10' SECOND) as end_time,
        | count(1) as c
        | from
        |words
        |group by word, TUMBLE(ts, INTERVAL '10' SECOND)
        |) as a
        |)as b
        |where r<=2
        |
      """.stripMargin)


  }

}
